package com.apgblogs.springbootstudy.service;

import com.apgblogs.springbootstudy.entity.SysRoleEntity;
import com.apgblogs.springbootstudy.entity.SysUserEntity;
import com.apgblogs.springbootstudy.repository.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;


/**
 * @author xiaomianyang
 * @description
 * @date 2019-05-15 13:11
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(final String login) throws UsernameNotFoundException {
        String lowerCaseLogin = login.toLowerCase();
        SysUserEntity sysUserEntity=sysUserRepository.findByUsernameCaseInsensitive(lowerCaseLogin);

        if(sysUserEntity==null){
            throw new UsernameNotFoundException("User"+lowerCaseLogin+"was not found in the database");
        }
        Collection<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        for(SysRoleEntity sysRoleEntity:sysUserEntity.getSysRoleEntities()){
            GrantedAuthority grantedAuthority=new SimpleGrantedAuthority(sysRoleEntity.getName());
            grantedAuthorities.add(grantedAuthority);
        }
        return new User(sysUserEntity.getUsername(),sysUserEntity.getPassword(),grantedAuthorities);
    }
}
